package service

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"path/filepath"
	"post/pkg"
	"time"
)

func OssUpload(c *gin.Context) {
	file, _ := c.FormFile("image")
	if file.Size > 1024*200 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "单张图片文件大小不超过200KB",
		})
		return
	}
	ext := filepath.Ext(file.Filename)
	if ext != ".jpg" && ext != ".png" && ext != ".gif" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "只允许上传JPG,PNG,GIF格式图片",
		})
		return
	}
	filename := fmt.Sprintf("upload/%s/%s", time.Now().Format("20060102"), file.Filename)
	c.SaveUploadedFile(file, "./"+filename)
	wd, _ := os.Getwd()
	url, err := pkg.OssUpload(filename, wd)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "OSS图片上传失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "OSS图片上传成功",
		"data": gin.H{
			"url": url,
		},
	})
	return
}
